package com.duke.payphone;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.duke.payphone.acct.AccountCreateActivity;
import com.duke.payphone.factory.MapFactory;


/**
 * Activity should manage login - ask for username and password
 * Also have a button to create a new account
 * 
 * user will enter login information; app does a quick validity check for
 * 'format' of pswd/username
 * 
 * app sends info to the server
 * 
 * server responds = valid (and returns a map of all users data), app stores
 * data in globalvars, proceed to ROOT
 * user data includes: user name, password, [all user acct info], all credit
 * card info (inc. last for digits of each credit card)
 * 
 * 
 * server responds = invalid, toast = "username/password invalid", stay here
 * 
 * Button: login, create account
 * 
 * @author Michael
 * 
 */
public class LoginActivity extends Activity {

    private EditText user;
    private EditText pswd;
    private Global globalvars;

    private String userStr;
    private String pswdStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // initialize application context
        globalvars = (Global) getApplicationContext();

        // initialize view fields
        user = (EditText) findViewById(R.id.et_un);
        pswd = (EditText) findViewById(R.id.et_pw);
        
        // set the stored username, if available
        user.setText(Global.username, TextView.BufferType.EDITABLE);

    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_login, menu);
        // return true;
        return false;
    }

    /**
     * redirect to create new user activity
     * if create new user fails, will return to this activity
     * 
     * @param v
     */
    public void createNewUser (View v) {
        Intent createAccount = new Intent(this, AccountCreateActivity.class);
        startActivity(createAccount);
    }

    /**
     * attempts to login
     * 
     * @param v
     */
    public void executeLogin (View v) {
        // grab data..
        updateData();

        // check validity
        if (checkData()) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onLoginValid(response);
                    }
                    else {
                        onLoginInvalid(response);
                    }
                }
                else {
                    // onSessionInvalid(); // does not happen for login
                }
            }
            else {
                onServerInvalid();
            }
        }
    }

    /**
     * Rereads the data from text fields
     */
    private void updateData () {
        userStr = user.getText().toString();
        pswdStr = pswd.getText().toString();
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {
        Map<String, Serializable> request = MapFactory.createTransmitMap("login");
        request.put("username", userStr);
        request.put("password", pswdStr);

        return request;
    }

    private boolean checkData () {
        // verify data is correct
        if (userStr.isEmpty() || pswdStr.isEmpty()) {
            // if incorrect, toast: [how to correct the data]
            Toast.makeText(globalvars, "Username/Password cannot be empty.", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }

        return true;
    }

    /**
     * Execute on valid login
     * 
     * @param response
     */
    private void onLoginValid (Map<String, Serializable> response) {
        // save sessionid
        if (response.containsKey("sessionid")) {
            Global.sessionid = (String) response.get("sessionid");
        }

        // save username
        if (response.containsKey("username")){
            Global.username = (String) response.get("username");
        }
        
        Toast.makeText(globalvars, "Login successful.", Toast.LENGTH_SHORT).show();

        // start root activity
        Intent toRoot = new Intent(this, RootActivity.class);
        startActivity(toRoot);
        // finish();
    }

    /**
     * Execute on invalid login
     * 
     * @param response
     */
    private void onLoginInvalid (Map<String, Serializable> response) {
        // toast that login was unsuccessful
        Toast.makeText(globalvars, "Login unsuccessful. Please try again.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        // request
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    // /**
    // * If session has timed out
    // */
    // private void onSessionInvalid () {
    // // reset the sessionID to null
    // Global.sessionid = "";
    //
    // // toast: current session has timed out
    // Toast.makeText(globalvars, "Current session has timed out.",
    // Toast.LENGTH_SHORT).show();
    //
    // // go back to the login screen
    // Intent toLogin = new Intent(this, LoginActivity.class);
    // toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // startActivity(toLogin);
    // finish();
    // }

}
